<?php


namespace App\Services;


use App\Enum\DriverEnum;
use App\Models\DriverCar;
use App\Models\DriverOthers;
use App\Models\Drivers;
use App\Models\User;
use App\Repositories\DriverRepository;
use App\Repositories\UserRepository;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;


class DriverService extends BaseService
{

    protected $repository;

    public function __construct()
    {
        $this->repository = new DriverRepository();
    }

    /**
     * 代驾司机信息保存
     */
    public function saveDatas(array $data)
    {
        $identity_photo = !empty($data['identity_photo']) ? $data['identity_photo'] : [];
        $licence_photo = !empty($data['licence_photo']) ? $data['licence_photo'] : [];
        DB::beginTransaction();
        try {
            if (empty($data['id'])) {
                $query = User::query()->where('phone', $data['phone'])->first();
                $driver = $this->repository->firstBy('phone', $data['phone'], 'id');

                if (!$query && !$driver) {
                    $data['status'] = '-1';   //申请司机状态改为未申请
                    // 注册会员
                    $user = User::query()->firstOrCreate(['phone' => $data['phone']], ['company_id' => $data['company_id']]);
                    $data['user_id'] = $user->id;
                    $data['type'] = '2'; //代驾模式
                    $driver = $this->repository->saveData($data);
                }
            } else {
                $map['real_name'] = $data['real_name'];
                $map['phone'] = $data['phone'];
                $map['identity'] = $data['identity'];

                $driver = Drivers::query()->updateOrCreate(['id' => $data['id']], $map);
            }
            $other = DriverOthers::query()->where('driver_id', $driver->id)->first();
            $driver_id = $driver ? $driver->id : 0;
            $oher = new  DriverOthers;
            if (!$other) {
                $oher->driver_id = $driver_id;
                $oher->company_id = $data['company_id'] ? $data['company_id'] : 1;
                $oher->province = $data['province'];
                $oher->identity_photo = [];
                $oher->licence_photo = [];
                $oher->city = $data['city'];
                $oher->identity_photo = $identity_photo;
                $oher->licence_photo = $licence_photo;
                $oher->auditor_id = 1;
                $oher->status = DriverEnum::JOB;
                $oher->balance = 0;
                $oher->source = (int)$data['source'];
                $oher->save();
            } else {
                $other->driver_id = $driver_id;
                $other->company_id = $data['company_id'];
                $other->province = $data['province'];
                $other->city = $data['city'];
                $other->identity_photo = $identity_photo;
                $other->licence_photo = $licence_photo;
                $other->auditor_id = 1;
                $other->status = DriverEnum::JOB;
                $other->balance = 0;
                $other->source = (int)$data['source'];
                $other->save();
            }
            if (!$driver) throw new Exception('保存失败');
            //修改司机手机号的同时修改用户手机号
            if (!empty($data['avatar'])) {
                $mmp = ['avatar' => $data['avatar'], 'phone' => $data['phone']];
            } else {
                $mmp = ['phone' => $data['phone']];
            }
            User::query()->where('id', $driver ? $driver->user_id : 0)->update($mmp);

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            return $this->setError($exception->getMessage());
        }
        return true;
    }

    /**
     * 保存司机信息
     * @param array $data
     * @return bool
     * @Author 姿势就是力量
     */
    public function saveData(array $data)
    {
        DB::beginTransaction();
        try {
            $car = [];
            if (isset($data['car'])) {
                $car = $data['car'];
                unset($data['car']);
            }

            $query = User::query()->where('phone', $data['phone']);

            // 验证手机号是否已注册
            if (isset($data['id']) && $data['id']) {
                (new DriverCar())->where('driver_id', $data['id'])->delete();
                if ($query->where('id', '!=', $data['user_id'])->exists()) {
                    throw new Exception('该手机号已注册用户');
                }
            } else {
                $driver = $this->repository->firstBy('phone', $data['phone'], 'id');
                if ($driver) throw new Exception('该手机号已注册司机');
                $data['status'] = DriverEnum::JOB;   //申请司机状态改为正常
                $data['taxi_status'] = DriverEnum::JOB;   //申请司机出租车改为正常
                // 注册会员
                $user = User::firstOrCreate(['phone' => $data['phone']], ['company_id' => $data['company_id']]);
                $data['user_id'] = $user->id;
            }

            $driver = $this->repository->saveData($data);
            if (!$driver) throw new Exception('保存失败');
            //修改司机手机号的同时修改用户手机号
            User::where('id', $driver->user_id)->update(['phone' => $data['phone']]);
            // 司机车辆信息
            if ($car) {
                $params = [];
                foreach ($car as $key => $item) {
                    $params[] = [
                        'car_id' => $item['id'],
                        'driver_id' => $driver->id,
                        'host' => $item['host'],
                    ];
                }
                (new DriverCar())->insert($params);
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();

            return $this->setError($e->getMessage());
        }

        return true;
    }


    /**
     * 修改密码
     * @param int $id 司机ID
     * @param string $password 密码
     * @return bool
     * @Author 姿势就是力量
     */
    public function savePassword(int $id, string $password)
    {
        $repository = new UserRepository();

        // 司机信息
        $driver = $this->repository->find($id, ['id', 'user_id']);
        if (!$driver) return $this->setError('未找到该司机');

        // 用户信息
        $user = $repository->find($driver->user_id, ['id', 'password']);
        if (!$user) return $this->setError('未找到该用户');
        $user->password = bcrypt($password);
        $user->save();

        return true;
    }


    /**
     * 更新司机状态
     * @param int $id 司机ID
     * @param string $status 状态
     * @return bool
     * @Author 姿势就是力量
     */
    public function saveState(int $id, string $status)
    {
        $data = [
            'id' => $id,
            'status' => $status
        ];

        // 审核，记录审核人及审核时间
        if (in_array($status, [DriverEnum::REJECT, DriverEnum::JOB])) {
            $data['auditor_id'] = session('adminInfo')['id'];
            $data['audit_time'] = Carbon::now();
        }
        $driver = $this->repository->saveData($data);
        if (!$driver) return $this->setError('更新失败');

        return true;
    }

    /**
     * @param int $id
     * @param string $status
     * @return bool
     * 代驾审核
     */
    public function saveStates(int $id, string $status)
    {
        $data = [
            'status' => $status
        ];
        // 审核，记录审核人及审核时间
        if (in_array($status, [DriverEnum::REJECT, DriverEnum::JOB])) {
            $data['auditor_id'] = session('adminInfo')['id'] ? session('adminInfo')['id'] : 1;
            $data['audit_time'] = Carbon::now();
        }

        $driver = DriverOthers::query()->where('driver_id', $id)->update($data);
        if (!$driver) return $this->setError('更新失败');

        return true;
    }

    /**
     * @param int $id
     * @param string $status
     * @return bool
     * 出租车审核
     */
    public function saveStatesss(int $id, string $status)
    {
        $data = [
            'id' => $id,
            'taxi_status' => $status
        ];

        // 审核，记录审核人及审核时间
        if (in_array($status, [DriverEnum::REJECT, DriverEnum::JOB])) {
            $data['auditor_id'] = session('adminInfo')['id'];
            $data['audit_time'] = Carbon::now();
        }
        $driver = $this->repository->saveData($data);
        if (!$driver) return $this->setError('更新失败');

        return true;
    }


}
